#!/usr/bin/python
# -*- coding: utf-8 -*-

import ImageFile
import django.forms as forms
import Image, ImageEnhance ,os
import datetime,time,string

des_origin_path = "D:\\home\\b.jpg"
DES_DIR_IMG = "D:\workspaceweb\JiaJu\src\jiaju\web\media\UploadImg"
if os.name != 'nt':
    DES_DIR_IMG = "/data"
POSITION = ('LEFTEND', 'RIGHTEND', 'CENTER', 'LEFTBOTTOM', 'RIGHTBOTTOM')
PADDING = 10
MARKIMAGE = 'water.png'


class PictureForm(forms.Form):
    imagefile = forms.ImageField()  

def reduce_opacity(im, opacity):
    """Returns an image with reduced opacity."""
    assert opacity >= 0 and opacity <= 1
    if im.mode != 'RGBA':
        im = im.convert('RGBA')
    else:
        im = im.copy()
    alpha = im.split()[3]
    alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
    im.putalpha(alpha)
    return im

def watermark(imagefile, markfile, position=POSITION[4], opacity=1):
    """Adds a watermark to an image."""   
    im = Image.open(imagefile)
    mark = Image.open(markfile)   
    if opacity < 1:
        mark = reduce_opacity(mark, opacity)
    if im.mode != 'RGBA':
        im = im.convert('RGBA')
    # create a transparent layer the size of the image and draw the
    # watermark in that layer.
    layer = Image.new('RGBA', im.size, (0, 0, 0, 0))
    if position == 'title':
        for y in range(0, im.size[1], mark.size[1]):
            for x in range(0, im.size[0], mark.size[0]):
                layer.paste(mark, (x, y))
    elif position == 'scale':
        # scale, but preserve the aspect ratio
        ratio = min(
            float(im.size[0]) / mark.size[0], float(im.size[1]) / mark.size[1])
        w = int(mark.size[0] * ratio)
        h = int(mark.size[1] * ratio)
        mark = mark.resize((w, h))
        layer.paste(mark, ((im.size[0] - w) / 2, (im.size[1] - h) / 2))
    elif position == POSITION[0]:
        #leftend
        position = (PADDING, im.size[1] - mark.size[1] - PADDING)
        layer.paste(mark, position)
    elif position == POSITION[1]:
        #rightend
        position = (im.size[0] - mark.size[0] - PADDING, im.size[1] - mark.size[1] - PADDING)
        layer.paste(mark, position)
    elif position == POSITION[2]:
        #center
        position = ((im.size[0] - mark.size[0]) / 2, (im.size[1] - mark.size[1]) / 2)
        layer.paste(mark, position)
    elif position == POSITION[3]:
        #left bottom
        position = (PADDING, im.size[1] - mark.size[1] - PADDING,)
        layer.paste(mark, position)
    else:
        #right bottom (default)
        position = (im.size[0] - mark.size[0] - PADDING, im.size[1] - mark.size[1] - PADDING,)
        layer.paste(mark, position)
    # composite the watermark with the layer
    return Image.composite(layer, im, layer)


def get_pic_abs_dir():
    localtime = time.localtime()
    year = time.strftime("%Y", localtime)
    month = time.strftime("%m", localtime)
    day = time.strftime("%d", localtime)
    absDir = "%s%s%s%s%s%s%s"%(os.sep, year , os.sep , month , os.sep , day , os.sep)
    absUrl = "%s%s%s%s%s%s%s"%('/', year , '/' , month , '/' , day , '/')
    return absDir,absUrl

def get_pic_dir(StorageDir=DES_DIR_IMG):
    absDir,absUrl = get_pic_abs_dir()
    StorageDir = "%s%s"%(StorageDir,absDir)
    return StorageDir,absDir,absUrl

def get_pic_name(id):
    localtime = time.localtime( time.time() )
    year = time.strftime("%Y", localtime)
    month = time.strftime("%m", localtime)
    day = time.strftime("%d", localtime)
    hour = time.strftime("%H", localtime)
    min = time.strftime( "%M", localtime )
    sec = time.strftime("%S",localtime)
    path = str(id)+"_"+year + "_" + month + "_" + day+"_" + hour + "_" + min + "_" + sec
    return path 

def get_img_fix(image):
    if image.format == "JPEG":
        return ".jpg" , image.format

def addPic(request,id):
    if id is None:
        return -1,""
    if request.method == "POST" :
       
            reqfile = request.FILES['imagefile']  
            image = Image.open(reqfile)
            fix,mode = get_img_fix(image)
            #image.thumbnail((128,128),Image.ANTIALIAS)
            StroageDir,absDir,absUrl = get_pic_dir()
            if os.path.exists(StroageDir) is not True:
                os.makedirs(StroageDir)
            file_name = StroageDir+get_pic_name(id)+fix
            abs_file_name = absUrl + get_pic_name(id) + fix
            print "abs###############%s"%abs_file_name
            print "file_name##################%s"%file_name
            image.save(file_name,mode)  
            #img.fs(DES_DIR_IMG)
            #img = watermark(img, "D:\\mark.jpg", position=POSITION[2], opacity=1)
            #img.fs(des_origin_path)
            return 1,abs_file_name
            
